/*
 * @Author: zheguo 3188606474@qq.com
 * @Date: 2024-04-19 18:55:10
 * @LastEditors: zheguo 3188606474@qq.com
 * @LastEditTime: 2024-04-21 09:15:43
 * @FilePath: \ProjectAction\projectOne\myexpress\app\controllers\user\user.controller.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const {where} = require("sequelize")
const db = require("../../models/index")
const Users = db.users
exports.create = (req, res) => {
    if (!req.body.username && !req.body.password) {
        res.status(400).send({
            message: "用户名和密码不能为空"
        })
        return
    }
    const dataTable = {
        username: req.body.username, password: req.body.password, address: req.body.address,
    }

    Users.create(dataTable).then(data => {
        if (data) {
            res.send({ok: 1})
            console.log(data)
        } else {
            res.send({ok: 0})
        }
    }).catch(err => {
        console.log(err.message + "创建数据出错")
    })
}

exports.findone = (req, res) => {
    Users.findOne({
        raw: true, where: {
            username: req.query.username, password: req.query.password
        }
    }).then((data) => {
        if (data) {
            res.send({ok: 1})
            console.log(data)
        } else {
            res.send({ok: 0})
        }
    }).catch(err => {
        console.log(err.message + "查询数据出错")

    })
}

exports.findAll = (req, res) => {
    Users.findAll().then((data) => {
        res.send({
            data: data, ok: 1
        })
    }).catch(err => {
        console.log(err.message + "查询数据出错")

    })
}

exports.delete = (req, res) => {

    Users.destroy({
        where: {
            id: req.query.id
        }
    }).then(data => {
        res.send({data: data, code: 102, message: "删除成功"})
    }).catch(err => {
        res.send({data: null, code: 202, message: "删除失败"})
    })
}

exports.update = (req, res) => {
    Users.update({
        username: req.body.username, password: req.body.password, address: req.body.address,
    }, {
        where: {
            id: req.body.id
        }
    }).then(data => {
        if (data[0] !== 0) {
            res.send({data: data, code: 101, message: "更新成功"})
        } else {
            res.send({data: null, code: 201, message: "更新失败"})
        }
    }).catch(err => {
        console.log(err)
    })
}